<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { useRoute } from 'vue-router';
import 'video.js/dist/video-js.css';
import videojs from 'video.js';
import { getCourseById } from '../services/api';

const route = useRoute();
const courseId = route.params.id;
const player = ref(null);
const videoContainer = ref(null);
const courseTitle = ref('加载中...');
const courseDescription = ref('');
const loading = ref(true);

onMounted(async () => {
  try {
    loading.value = true;
    
    // 获取课程详情
    const courseData = await getCourseById(courseId);
    
    if (courseData) {
      courseTitle.value = courseData.title;
      courseDescription.value = courseData.description;
      
      // 获取视频URL
      const videoUrl = courseData.video_url || courseData.videoUrl;
      
      if (!videoUrl) {
        console.error('视频URL不存在');
        courseTitle.value = '视频资源不可用';
        return;
      }
      
      // 根据URL后缀判断视频类型
      let videoType = 'video/mp4'; // 默认类型
      if (videoUrl.endsWith('.webm')) {
        videoType = 'video/webm';
      } else if (videoUrl.endsWith('.ogg') || videoUrl.endsWith('.ogv')) {
        videoType = 'video/ogg';
      } else if (videoUrl.endsWith('.mov')) {
        videoType = 'video/quicktime';
      } else if (videoUrl.endsWith('.m3u8')) {
        videoType = 'application/x-mpegURL';
      }
      
      // 尝试验证视频URL是否可访问
      try {
        // 创建一个临时的视频元素来测试URL
        const testVideo = document.createElement('video');
        testVideo.style.display = 'none';
        testVideo.src = videoUrl;
        
        // 添加测试事件
        testVideo.addEventListener('error', () => {
          console.error('视频URL测试失败，尝试使用备用播放方式');
          // 如果测试失败，尝试使用HTML5原生播放器
          initializeNativePlayer(videoUrl);
        });
        
        testVideo.addEventListener('loadedmetadata', () => {
          // URL有效，使用videojs播放器
          initializeVideoJsPlayer(videoUrl, videoType);
          document.body.removeChild(testVideo);
        });
        
        // 添加到DOM并开始加载
        document.body.appendChild(testVideo);
        
        // 设置超时，如果5秒内没有响应，则尝试备用方式
        setTimeout(() => {
          if (document.body.contains(testVideo)) {
            document.body.removeChild(testVideo);
            console.warn('视频加载超时，尝试使用备用播放方式');
            initializeNativePlayer(videoUrl);
          }
        }, 5000);
      } catch (e) {
        console.error('视频URL测试出错:', e);
        // 出错时直接使用videojs尝试播放
        initializeVideoJsPlayer(videoUrl, videoType);
      }
      
      // 初始化VideoJS播放器
      function initializeVideoJsPlayer(url, type) {
        player.value = videojs(videoContainer.value, {
          controls: true,
          autoplay: false,
          preload: 'auto',
          fluid: true,
          playbackRates: [0.5, 1, 1.25, 1.5, 2],
          sources: [{
            src: url,
            type: type
          }],
          html5: {
            hls: {
              overrideNative: true
            },
            nativeVideoTracks: false,
            nativeAudioTracks: false,
            nativeTextTracks: false
          }
        });
        
        // 添加错误处理
        player.value.on('error', function() {
          const error = player.value.error();
          console.error('视频播放错误:', error);
          
          // 如果VideoJS播放失败，尝试使用原生播放器
          if (!document.querySelector('.native-video-player')) {
            console.log('VideoJS播放失败，尝试使用原生播放器');
            player.value.dispose();
            initializeNativePlayer(url);
          } else {
            // 显示友好的错误信息
            const errorDisplay = document.createElement('div');
            errorDisplay.className = 'vjs-error-display bg-gray-800 text-white p-4 rounded';
            errorDisplay.innerHTML = `
              <div class="text-center">
                <p class="text-xl mb-2">视频无法播放</p>
                <p class="text-sm">可能原因: ${error ? error.message : '未知错误'}</p>
                <p class="text-sm mt-2">请检查视频URL是否正确，或者视频格式是否受支持</p>
                <p class="text-sm">视频URL: ${url}</p>
              </div>
            `;
            
            // 替换原有的错误显示
            const oldErrorDisplay = document.querySelector('.vjs-error-display');
            if (oldErrorDisplay) {
              oldErrorDisplay.parentNode.replaceChild(errorDisplay, oldErrorDisplay);
            }
          }
        });
      }
      
      // 初始化原生HTML5播放器（作为备用）
      function initializeNativePlayer(url) {
        // 清除videojs播放器
        if (player.value) {
          player.value.dispose();
          player.value = null;
        }
        
        // 创建原生播放器
        const nativePlayer = document.createElement('div');
        nativePlayer.className = 'native-video-player';
        nativePlayer.innerHTML = `
          <video 
            controls 
            preload="auto" 
            class="w-full h-full rounded-lg"
            style="max-height: 70vh;"
            crossorigin="anonymous"
          >
            <source src="${url}" />
            <p class="text-center p-4 bg-gray-800 text-white">您的浏览器不支持HTML5视频播放</p>
          </video>
          <div class="text-center text-gray-500 text-sm mt-2">
            使用浏览器原生播放器播放
          </div>
        `;
        
        // 替换播放器容器内容
        const container = videoContainer.value.parentNode;
        container.innerHTML = '';
        container.appendChild(nativePlayer);
        
        // 添加错误处理
        const videoElement = nativePlayer.querySelector('video');
        videoElement.addEventListener('error', (e) => {
          console.error('原生播放器错误:', e);
          nativePlayer.innerHTML = `
            <div class="bg-gray-800 text-white p-4 rounded text-center">
              <p class="text-xl mb-2">视频无法播放</p>
              <p class="text-sm">所有可用播放方式均已尝试，但视频仍无法播放</p>
              <p class="text-sm mt-2">请检查视频URL是否正确: ${url}</p>
            </div>
          `;
        });
      }
    } else {
      courseTitle.value = '课程不存在';
    }
  } catch (error) {
    console.error('加载课程详情失败:', error);
    courseTitle.value = '加载失败';
  } finally {
    loading.value = false;
  }
});

// 组件销毁时释放播放器资源
onBeforeUnmount(() => {
  if (player.value) {
    player.value.dispose();
  }
});
</script>

<template>
  <div>
    <div class="mb-6">
      <h1 class="text-2xl font-bold">{{ courseTitle }}</h1>
    </div>
    
    <div class="video-container bg-black rounded-lg overflow-hidden shadow-xl">
      <video
        ref="videoContainer"
        class="video-js vjs-big-play-centered"
        controls
        preload="auto"
      ></video>
    </div>
    
    <div class="mt-8 bg-white p-6 rounded-lg shadow">
      <h2 class="text-xl font-semibold mb-4">课程简介</h2>
      <p v-if="loading" class="text-gray-500">加载中...</p>
      <p v-else-if="courseDescription" class="text-gray-700">
        {{ courseDescription }}
      </p>
      <p v-else class="text-gray-500">暂无课程简介</p>
    </div>
  </div>
</template>

<style scoped>
.video-container {
  max-width: 100%;
  margin: 0 auto;
  position: relative;
  width: 100%;
  padding-top: 56.25%; /* 16:9比例 (9/16 = 0.5625 = 56.25%) */
}

.video-container :deep(.video-js),
.video-container :deep(.native-video-player),
.video-container :deep(video) {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

/* 确保移动端按钮尺寸合适 */
:deep(.vjs-button) {
  min-width: 44px;
  min-height: 44px;
}
</style>